package com.dcm.groupbuy.service.impl;

import com.dcm.common.constant.Constants;
import com.dcm.common.exception.MyException;
import com.dcm.common.service.RedisService;
import com.dcm.common.utils.IdWorker;
import com.dcm.common.vo.CommonResponse;
import com.dcm.groupbuy.bo.OrderBo;
import com.dcm.groupbuy.entity.GroupOrderEntity;
import com.dcm.groupbuy.mapper.GroupOrderMapper;
import com.dcm.groupbuy.mapper.OrderBoMapper;
import com.dcm.groupbuy.service.OrderBoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author 牛浩
 */
@Service
public class OrderBoServiceImpl implements OrderBoService {
    @Autowired
    private OrderBoMapper orderBoMapper;
    @Autowired
    private GroupOrderMapper groupOrderMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public CommonResponse startGroup(Long id, String name) throws MyException {
        if (id == null) {
            throw new MyException(Constants.GroupBoErrorMsg.ID_CANNOT_NULL);
        }
        if (name == null) {
            throw new MyException(Constants.GroupBoErrorMsg.NOTE_CANNOT_NULL);
        }
        /**
         * 判断团购商品是不是已经买完
         */
        List<GroupOrderEntity> all = (List<GroupOrderEntity>) redisService.get("开团");
        for (GroupOrderEntity groupOrderEntity : all) {
            if (groupOrderEntity.getGroupId().equals(id - 1) & groupOrderEntity.getJoinPeople().equals(groupOrderEntity.getGroupPeople())) {
                //进入if 代表团购商品已经买完 退出并返回信息
                return new CommonResponse(0, Constants.GroupBoErrorMsg.OK_CANNOT_NULL);
            }
        }
        /**
         *redis查询全部
         */
        boolean flag = false;
        List<OrderBo> orderEntityList = (List<OrderBo>) redisService.get("参团");
        for (OrderBo orderBo : orderEntityList) {
            if (orderBo != null && orderBo.getOrderSn().equals(id + "") && orderBo.getMemberUsername().equals(name)) {
                /**
                 * 判断传过来的id和name 如果有这条数据 证明已经拼过团 赋flag标识符为 true
                 */
                flag = true;
            }
        }
        if (flag == true) {
            /**
             * 如果有该数据 则退出
             */
            throw new MyException(Constants.GroupBoErrorMsg.MESSAGE);
        }else {
            //如果没有该数据
            return insertOrder(orderEntityList, id, name);
        }
    }

    public CommonResponse insertOrder(List<OrderBo> orderEntityList, Long id, String name) {
        /**
         * 先查询所有发起拼团人数据
         */
        List<GroupOrderEntity> all = (List<GroupOrderEntity>) redisService.get("开团");
        OrderBo order = new OrderBo();
        for (OrderBo orderBo : orderEntityList) {
            /**
             * 根据id查询发起拼团人的信息
             */
            if (orderBo != null && orderBo.getId().equals(id)) {
                order = orderBo;
            }
        }
        /**
         * 创建一个空的实体类准备赋值
         */
        OrderBo orderBo = new OrderBo();
        Long groupId = null;
        Integer joinPeople = null;
        boolean flag1 = false;
        boolean flag2 = false;

        for (GroupOrderEntity orderEntity : all) {
            if (orderEntity != null && orderEntity.getTeamLeader().equals(order.getReceiverName()) && orderEntity.getGroupId().equals(order.getId() - 1) && orderEntity.getGroupName().equals(order.getNote()) && orderEntity.getGroupState() == 1 && orderEntity.getEndDate().compareTo(new Date()) >= -1) {
                /**
                 * 如果拼团商品在时间段内 拼团活动是开启的 商品名称相同 开启拼团人相同 则 添加拼团成员
                 */
                flag1 = true;
                orderBo.setId(new IdWorker().nextId());
                orderBo.setMemberUsername(name);
                orderBo.setOrderSn(order.getOrderSn());
                orderBo.setReceiverName(order.getReceiverName());
                orderBo.setNote(order.getNote());
                /**
                 * 添加redis
                 */
                ArrayList<OrderBo> orderBoArrayList = new ArrayList<>();
                List<OrderBo> orders = (List<OrderBo>) redisService.get("参团");
                for (OrderBo bo : orders) {
                    orderBoArrayList.add(bo);
                }
                if (orders != null) {
                    orderBoArrayList.add(orderBo);
                    redisService.set("参团", orderBoArrayList, 86400);
                    flag2 = true;
                }
                groupId = orderEntity.getGroupId();
                joinPeople = orderEntity.getJoinPeople();
                if (flag2 == true) {
                    break;
                }
            }
        }
        if (flag1 == false) {
            /**
             * 如果拼团条件不满足 则退出
             */
            throw new MyException(Constants.GroupBoErrorMsg.CONDITIONS_NOT_SATISFIED);
        }
        /**
         * 添加拼团成员
         */
        orderBoMapper.insertOrderBo(orderBo);
        /**
         * 修改发起拼团人 已拼团人数
         */
        for (GroupOrderEntity groupOrderEntity : all) {
            if (groupOrderEntity != null && groupId.equals(groupOrderEntity.getGroupId())) {
                //如果发起拼团人不为空 并且 主键等于传过来的id
                groupOrderEntity.setJoinPeople(groupOrderEntity.getJoinPeople() + 1);
            }
        }
        redisService.set("开团", all, 86400);
        groupOrderMapper.updatePeople(groupId, joinPeople + 1);
        /**
         * 根据id查询发起拼团人数据
         */
        GroupOrderEntity groupOrderEntity = groupOrderMapper.findById(groupId);
        boolean flag3 = false;
        if (groupOrderEntity.getJoinPeople().equals(groupOrderEntity.getGroupPeople())==true || groupOrderEntity.getEndDate().compareTo(new Date()) == -1) {
            /**
             * 如果拼团人数等于拼团成功需要的人数  则拼团完成 关闭拼团  或者结束时间已过 关闭拼团
             */
            flag3 = true;
            groupOrderMapper.update(groupOrderEntity.getGroupId());
        }
        if (flag3) {
            return new CommonResponse(0, Constants.GroupBoErrorMsg.END_CANNOT_NULL);
        } else {
            return new CommonResponse(0, Constants.GroupBoErrorMsg.START_CANNOT_NULL);
        }
    }


    @Override
    public OrderBo findById(Long id) {
        if (id == null) {
            throw new MyException(Constants.GroupBoErrorMsg.ID_CANNOT_NULL);
        }
        OrderBo byId = orderBoMapper.findById(id);
        return byId;
    }

    @Override
    public void mySeIf(String note,String memberUsername) {
        Long id = new IdWorker().nextId();
        orderBoMapper.mySeIf(id,memberUsername,note);
    }

    @Override
    public PageInfo<OrderBo> findPage(Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<OrderBo> list = orderBoMapper.findAll();
        PageInfo<OrderBo> page = new PageInfo<>(list);
        return page;
    }

    private static void checkOrderBo(OrderBo orderBo) {
        if (orderBo.getNote() == null) {
            throw new MyException(Constants.GroupBoErrorMsg.NOTE_CANNOT_NULL);
        }
        if (orderBo.getOrderSn() == null) {
            throw new MyException(Constants.GroupBoErrorMsg.ORDER_SN_CANNOT_NULL);
        }
        if (orderBo.getReceiverName() == null) {
            throw new MyException(Constants.GroupBoErrorMsg.RECEIVER_NAME_CANNOT_NULL);
        }
        if (orderBo.getMemberUsername() == null) {
            throw new MyException(Constants.GroupBoErrorMsg.MEMBER_USERNAME_CANNOT_NULL);
        }
    }
}